/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package pe.edu.pucp.cpnc.mm.clientview;

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

/**
 *
 * @author Lambda
 */
public class MapViewerPanel extends javax.swing.JPanel implements MouseListener, KeyListener {
    public static final int Anchura = 96;
    public static final int Altura = 48;
    public static final int offsetX = 100;
    public static final int offsetY = 300;
    public double xReal=0;
    public double yReal=0;
    public double xRealOld = 0;
    public double yRealOld = 0;
    protected double mouseX;
    protected double mouseY;
    public pe.edu.pucp.cpnc.mm.bean.Object selObj = null;
    
    private RefreshThread myThread;
    
    private class RefreshThread extends Thread{
        MapViewerPanel p;
        
        @Override
        public void run(){
            while(true){
               Point point = MouseInfo.getPointerInfo().getLocation();
               Point point2;
               try{
                    point2 = p.getLocationOnScreen();
               }catch(Exception e){
                    point2 = new Point(0, 0);
               } 
               p.mouseX = point.getX() - point2.getX();
               p.mouseY = point.getY() - point2.getY();
                
               repaint();
               
               try{
               Thread.sleep((int)(1000/30));
               }catch(Exception e){e.printStackTrace();}
            }
        }
        
        public RefreshThread(MapViewerPanel panel){
            p = panel;
        }
    }
    
    /**
     * Creates new form MapViewerPanel
     */
    @SuppressWarnings("LeakingThisInConstructor")
    public MapViewerPanel() {
        initComponents();
        this.setFocusable(true);
        setLayout(new BorderLayout());
        this.addMouseListener(this);
        this.addKeyListener(this);
        this.setDoubleBuffered(true);
        myThread = new RefreshThread(this);
        myThread.start();
    }
	
    @Override
    public void paint(Graphics g){
        super.paint(g);
        ImageIcon img;
        try{
            int j = (int)Math.round(((mouseX - offsetX)/(double)Anchura) - ((mouseY - offsetY)/(double)Altura));//j
            int i = (int)Math.round(((mouseX - offsetX)/(double)Anchura) + ((mouseY - offsetY)/(double)Altura))-1;//i
            
            img =MainWindow.proxy.printMap(getWidth(),getHeight(), j, i, selObj);
        }catch(RemoteException e){
            e.printStackTrace();
            img = null;
        }
        
        if(img != null) g.drawImage(img.getImage(), 0, 0, this);
    }
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        addContainerListener(new java.awt.event.ContainerAdapter() {
            public void componentRemoved(java.awt.event.ContainerEvent evt) {
                formComponentRemoved(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void formComponentRemoved(java.awt.event.ContainerEvent evt) {//GEN-FIRST:event_formComponentRemoved
        try {
            myThread.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(MapViewerPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_formComponentRemoved


    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables

    @Override
    public void mouseClicked(MouseEvent e) {
       
    }

    @Override
    public void mousePressed(MouseEvent e) {
        if(e.getButton() == MouseEvent.BUTTON3){
            xRealOld=(double)e.getX();
            yRealOld=(double)e.getY();
        }
        
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        xReal=(double)e.getX();
        yReal=(double)e.getY();
        
        if(!this.isFocusOwner()) this.requestFocus();
        
        if(e.getButton() == MouseEvent.BUTTON1){ //Agrega una unidad
            
            
            int j = (int)Math.round(((xReal - offsetX)/(double)Anchura) - ((yReal - offsetY)/(double)Altura));//j
            int i = (int)Math.round(((xReal - offsetX)/(double)Anchura) + ((yReal - offsetY)/(double)Altura))-1;//i
           
            try{
                if(MapViewerFrame.selectedTile !=-1)        
                    MainWindow.proxy.changeTile(j, i, MainWindow.resources.getAvailableTiles().get(MapViewerFrame.selectedTile));
                else if(selObj != null)
                    MainWindow.proxy.addObject(j, i, selObj, 1);
                
            }catch(RemoteException e3){
                e3.printStackTrace();
            }
            //repaint
        }
        
        //Mueve un objeto
        if(e.getButton() == MouseEvent.BUTTON3 && ((xReal != xRealOld) || (yReal != yRealOld)) ){
            int j = (int)Math.round(((xReal - offsetX)/(double)Anchura) - ((yReal - offsetY)/(double)Altura));//j
            int i = (int)Math.round(((xReal - offsetX)/(double)Anchura) + ((yReal - offsetY)/(double)Altura))-1;//i
            int j2 = (int)Math.round(((xRealOld - offsetX)/(double)Anchura) - ((yRealOld - offsetY)/(double)Altura));//j
            int i2 = (int)Math.round(((xRealOld - offsetX)/(double)Anchura) + ((yRealOld - offsetY)/(double)Altura))-1;//i
            
            try{
                MainWindow.proxy.updateObject(j2, i2, j, i);
            }catch(Exception e1){}
            //repaint();
        }
    }

    @Override
    public void mouseEntered(MouseEvent e) {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void mouseExited(MouseEvent e) {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_DELETE){
            int j = (int)Math.round(((xReal - offsetX)/(double)Anchura) - ((yReal - offsetY)/(double)Altura));//j
            int i = (int)Math.round(((xReal - offsetX)/(double)Anchura) + ((yReal - offsetY)/(double)Altura))-1;//i
            
            try{
                MainWindow.proxy.eraseObject(j, i);
            }catch(RemoteException e2){}
            //repaint();
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }
}
